package com.example.server.security;

import com.example.common.exception.YebException;
import com.example.common.vo.RespBean;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RequiredInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            MethodParameter[] methodParameters1 = handlerMethod.getMethodParameters();
            for (MethodParameter methodParameter : methodParameters1) {
                MyRequired methodAnnotation = methodParameter.getParameterAnnotation(MyRequired.class);
                if(methodAnnotation != null){
                    String  parameterAge = methodParameter.getParameter().getName();
                    String parameter = request.getParameter(parameterAge);
                    if(parameter.trim().length() == 0){
                        throw new YebException(403,parameterAge + "参数age不能为空");
                    }
                    if( Integer.parseInt(parameter.trim()) > 100 ||  Integer.parseInt(parameter.trim()) < 18){
                        throw new YebException(403, "age大于100或者age小于18");
                    }
                }
            }

            MyRequired methodAnnotation = handlerMethod.getMethodAnnotation(MyRequired.class);

            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();

            if (methodParameters != null || methodParameters.length != 0  ) {
                if (methodAnnotation != null) {

                    return true;

                }
            }
        }
        return true;
    }
}
